﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.IO.Ports;



namespace YBOT_Field_Control
{

    public partial class Main_Control : Form
    {

        #region Variables

        OneWire ow = new OneWire();
        XBee xb = new XBee();
        LogWriter lw = new LogWriter();
        Time time = new Time();
        Field_Control fc;
        Game game;

        Game_Display GD = new Game_Display();

        private bool done = true;
        private bool toggle = false;
        private int selectedTower = 0;
        private int matchNumber = 0;


        #endregion

        //Constructor
        public Main_Control()
        {
            //Start Form
            InitializeComponent();

            //Initialize Field Controls
            this.fc = new Field_Control(ow, xb);

            //Start game
            game = new Game(this.fc);
        }

        //When Window loads
        private void Main_Control_Load(object sender, EventArgs e)
        {

        }

        //When Window is shown
        private void Main_Control_Shown(object sender, EventArgs e)
        {
            this.game.begin();           //Begin Game
            this.ow.Startup();           //Start 1 wire

            cbXbeeComPort.Items.Clear();
            foreach (string portname in SerialPort.GetPortNames())
            {
                cbXbeeComPort.Items.Add(portname);
                cbXbeeComPort.Text = portname.ToString();
            }
            this.xb.Startup(cbXbeeComPort.Text);       //Locate XBee Nodes
        }
     
        //When Window is closed
        private void Main_Control_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.fc.FieldAllOff();
            this.ow.HubAllOff();                         //Turn off 1 wire hubs
            done = true;                            //Done = true
            toggle = !toggle;                       //flip toggle
            this.game.STOP = true;                       //Stop game

            frmLocate_Nodes.clicked = true;         //Get focus
            frmLocate_Nodes.allDone = true;         //Click all done
            this.xb.Shutdown();                          //Shutdown XBee
        }

        //When tab is clicked
        private void tabYBOT_Click(object sender, EventArgs e)
        {
            cbXbeeComPort.Items.Clear();
            foreach (string portname in SerialPort.GetPortNames())
            {
                cbXbeeComPort.Items.Add(portname);
            }

        }

        #region Field Control Tab

        #region Control Buttons

        private void btnXBMode_Click(object sender, EventArgs e)
        {
        }

        #endregion

        #region Tower Buttons

        private void btnTower1_Click(object sender, EventArgs e)
        {
            selectedTower = 1;
            TowerUpdate(selectedTower);
        }

        private void btnTower2_Click(object sender, EventArgs e)
        {
            selectedTower = 2;
            TowerUpdate(selectedTower);
        }

        private void btnTower3_Click(object sender, EventArgs e)
        {
            selectedTower = 3;
            TowerUpdate(selectedTower);
        }

        private void btnTower4_Click(object sender, EventArgs e)
        {
            selectedTower = 4;
            TowerUpdate(selectedTower);
        }

        private void btnTower5_Click(object sender, EventArgs e)
        {
            selectedTower = 5;
            TowerUpdate(selectedTower);
        }

        private void btnTower6_Click(object sender, EventArgs e)
        {
            selectedTower = 6;
            TowerUpdate(selectedTower);
        }

        private void btnTower7_Click(object sender, EventArgs e)
        {
            selectedTower = 7;
            TowerUpdate(selectedTower);
        }

        private void btnTower8_Click(object sender, EventArgs e)
        {
            selectedTower = 8;
            TowerUpdate(selectedTower);
        }

        private void btnTower9_Click(object sender, EventArgs e)
        {
            selectedTower = 9;
            TowerUpdate(selectedTower);
        }

        private void btnTower10_Click(object sender, EventArgs e)
        {
            selectedTower = 10;
            TowerUpdate(selectedTower);
        }

        private void btnTower11_Click(object sender, EventArgs e)
        {
            selectedTower = 11;
            TowerUpdate(selectedTower);
        }

        private void btnTower12_Click(object sender, EventArgs e)
        {
            selectedTower = 12;
            TowerUpdate(selectedTower);
        }

        private void btnTower13_Click(object sender, EventArgs e)
        {
            selectedTower = 13;
        }

        private void btnTower14_Click(object sender, EventArgs e)
        {
            selectedTower = 14;
            TowerUpdate(selectedTower);
        }

        private void btnControlBoard_Click(object sender, EventArgs e)
        {
            selectedTower = 0;
            TowerUpdate(selectedTower);
        }

        private void btnLocatedCoupler_Click(object sender, EventArgs e)
        {
           DialogResult _result = MessageBox.Show("Do you want to change the coupler order or add a new tower?", "Locate Coupler", 
                                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
           if (_result == DialogResult.Yes)
           {
               string _file = this.ow.GetConfigFiles(false);
               string newFile = _file + ".old";
               try
               {
                       if (File.Exists(newFile))                                     
                       {
                           File.Delete(newFile);
                       }
                       if (File.Exists(_file))
                       {
                           File.Move(_file, newFile);
                       }
                       this.ow.LocateCoupler();
               }
               catch
               {
                   MessageBox.Show("Opps, something unexpected happened", "Error");
               }
           }
           else this.ow.LocateCoupler();
        }

        private void btnLocateTowers_Click(object sender, EventArgs e)
        {
            DialogResult _result = MessageBox.Show("Do you want to change the tower order or add a new tower?", "Locate Towers",
                                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (_result == DialogResult.Yes)
            {
                string _file = this.ow.GetConfigFiles(true);
                string newFile = _file + ".old";
                try
                {
                        if (File.Exists(newFile))
                        {
                            File.Delete(newFile);
                        }
                        if (File.Exists(_file))
                        {
                            File.Move(_file, newFile);
                        }
                        this.ow.Locate_Nodes();
                }
                catch
                {
                    MessageBox.Show("Opps, something unexpected happened", "Error");
                }
            }
            else this.ow.Locate_Nodes();
        }

        private void btnAllTowersOn_Click(object sender, EventArgs e)
        {
            this.fc.AllLights(true);
            TowerUpdate(selectedTower);
        }

        private void btnAllTowersOff_Click(object sender, EventArgs e)
        {
            this.fc.AllLights(false);
            TowerUpdate(selectedTower);
        }

        private void btnTowerStatus_Click(object sender, EventArgs e)
        {

            done = !done;
            while (!done)
            {
                Application.DoEvents();
                btnTowerStatus.Text = "Updating Tower Status";
                btnTowerStatus.ForeColor = Color.Green;
                for (int i = 1; i < this.ow.owNode.Length; i++)
                {
                    TowerUpdate(i);
                }
                RelayUpdate(selectedTower);
            }
            btnTowerStatus.Text = "Tower Status";
            btnTowerStatus.ForeColor = DefaultForeColor;
        }

        private void TowerUpdate(int towerNum)
        {
            string towerstatus;
            byte status;

            status = this.fc.ReadState(towerNum);
            towerstatus = status.ToString();

            if (towerNum == 1) lblTower1.Text = towerstatus;
            else if (towerNum == 2) lblTower2.Text = towerstatus;
            else if (towerNum == 3) lblTower3.Text = towerstatus;
            else if (towerNum == 4) lblTower4.Text = towerstatus;
            else if (towerNum == 5) lblTower5.Text = towerstatus;
            else if (towerNum == 6) lblTower6.Text = towerstatus;
            else if (towerNum == 7) lblTower7.Text = towerstatus;
            else if (towerNum == 8) lblTower8.Text = towerstatus;
            else if (towerNum == 9) lblTower9.Text = towerstatus;
            else if (towerNum == 10) lblTower10.Text = towerstatus;
            else if (towerNum == 11) lblTower11.Text = towerstatus;
            else if (towerNum == 12) lblTower12.Text = towerstatus;
            else if (towerNum == 13) lblTower13.Text = towerstatus;
            else if (towerNum == 14) lblTower14.Text = towerstatus;
            else if (towerNum == 15) lblControlBoard.Text = towerstatus;
        }

        private void btnUpdateStatus_Click(object sender, EventArgs e)
        {
            TowerUpdate(selectedTower);
            RelayUpdate(selectedTower);
        }

        #endregion

        #region Relay Buttons

        private void RelayUpdate(int towerNum)
        {
            if (this.fc.PinRead(1, selectedTower)) btnRelay1.ForeColor = Color.Red;
            else btnRelay1.ForeColor = DefaultForeColor;
            if (this.fc.PinRead(2, selectedTower)) btnRelay2.ForeColor = Color.Red;
            else btnRelay2.ForeColor = DefaultForeColor;
            if (this.fc.PinRead(3, selectedTower)) btnRelay3.ForeColor = Color.Red;
            else btnRelay3.ForeColor = DefaultForeColor;
            if (this.fc.PinRead(4, selectedTower)) btnRelay4.ForeColor = Color.Red;
            else btnRelay4.ForeColor = DefaultForeColor;
            if (this.fc.PinRead(5, selectedTower)) btnRelay5.ForeColor = Color.Red;
            else btnRelay5.ForeColor = DefaultForeColor;
            if (this.fc.PinRead(6, selectedTower)) btnRelay6.ForeColor = Color.Red;
            else btnRelay6.ForeColor = DefaultForeColor;
            if (this.fc.PinRead(7, selectedTower)) btnRelay7.ForeColor = Color.Red;
            else btnRelay7.ForeColor = DefaultForeColor;
            if (this.fc.PinRead(8, selectedTower)) btnRelay8.ForeColor = Color.Red;
            else btnRelay8.ForeColor = DefaultForeColor;
        }

        private void btnRelay1_Click(object sender, EventArgs e)
        {
            if (!this.fc.PinRead(selectedTower, 1))
            {
                this.fc.PinWrite(selectedTower, 1, true);
                btnRelay1.ForeColor = Color.Red;
            }
            else
            {
                this.fc.PinWrite(selectedTower, 1, false);
                btnRelay1.ForeColor = DefaultForeColor;
            }
            TowerUpdate(selectedTower);

        }

        private void btnRelay2_Click(object sender, EventArgs e)
        {
            if (!this.fc.PinRead(selectedTower, 2))
            {
                this.fc.PinWrite(selectedTower, 2, true);
                btnRelay2.ForeColor = Color.Red;
            }
            else
            {
                this.fc.PinWrite(selectedTower, 2, false);
                btnRelay2.ForeColor = DefaultForeColor;
            }
            TowerUpdate(selectedTower);
        }

        private void btnRelay3_Click(object sender, EventArgs e)
        {
            if (!this.fc.PinRead(selectedTower, 3))
            {
                this.fc.PinWrite(selectedTower, 3, true);
                btnRelay3.ForeColor = Color.Red;
            }
            else
            {
                this.fc.PinWrite(selectedTower, 3, false);
                btnRelay3.ForeColor = DefaultForeColor;
            }
            TowerUpdate(selectedTower);
        }

        private void btnRelay4_Click(object sender, EventArgs e)
        {
            if (!this.fc.PinRead(selectedTower, 4))
            {
                this.fc.PinWrite(selectedTower, 4, true);
                btnRelay4.ForeColor = Color.Red;
            }
            else
            {
                this.fc.PinWrite(selectedTower, 4, false);
                btnRelay4.ForeColor = DefaultForeColor;
            }
            TowerUpdate(selectedTower);
        }

        private void btnRelay5_Click(object sender, EventArgs e)
        {
            if (!this.fc.PinRead(selectedTower, 5))
            {
                this.fc.PinWrite(selectedTower, 5, true);
                btnRelay5.ForeColor = Color.Red;
            }
            else
            {
                this.fc.PinWrite(selectedTower, 5, false);
                btnRelay5.ForeColor = DefaultForeColor;
            }
            TowerUpdate(selectedTower);
        }

        private void btnRelay6_Click(object sender, EventArgs e)
        {
            if (!this.fc.PinRead(selectedTower, 6))
            {
                this.fc.PinWrite(selectedTower, 6, true);
                btnRelay6.ForeColor = Color.Red;
            }
            else
            {
                this.fc.PinWrite(selectedTower, 6, false);
                btnRelay6.ForeColor = DefaultForeColor;
            }
            TowerUpdate(selectedTower);
        }

        private void btnRelay7_Click(object sender, EventArgs e)
        {
            if (!this.fc.PinRead(selectedTower, 7))
            {
                this.fc.PinWrite(selectedTower, 7, true);
                btnRelay7.ForeColor = Color.Red;
            }
            else
            {
                this.fc.PinWrite(selectedTower, 7, false);
                btnRelay7.ForeColor = DefaultForeColor;
            }
            TowerUpdate(selectedTower);
        }

        private void btnRelay8_Click(object sender, EventArgs e)
        {
            if (!this.fc.PinRead(selectedTower, 8))
            {
                this.fc.PinWrite(selectedTower, 8, true);
                btnRelay8.ForeColor = Color.Red;
            }
            else
            {
                this.fc.PinWrite(selectedTower, 8, false);
                btnRelay8.ForeColor = DefaultForeColor;
            }
            TowerUpdate(selectedTower);
        }

        private void btnAllRelaysOn_Click(object sender, EventArgs e)
        {
            this.fc.AllPinsWrite(selectedTower, true);
            TowerUpdate(selectedTower);
        }

        private void btnAllRealysOff_Click(object sender, EventArgs e)
        {
            this.fc.AllPinsWrite(selectedTower, false);
            TowerUpdate(selectedTower);
        }

        private void btnRelayStatus_Click(object sender, EventArgs e)
        {
            RelayUpdate(selectedTower);
        }

        #endregion

        #region Test Buttons

        private void btnTestSomething_Click(object sender, EventArgs e)
        {

        }

        private void btnTestSomething2_Click(object sender, EventArgs e)
        {

        }

        private void btnTestSomething3_Click(object sender, EventArgs e)
        {
        }

        private void btnTestSomething4_Click(object sender, EventArgs e)
        {

        }

        private void btnDemo_Click(object sender, EventArgs e)
        {
            toggle = !toggle;

            if (toggle) btnDemo.BackColor = Color.Green;
            else btnDemo.BackColor = frmLocate_Nodes.DefaultBackColor;

            while (toggle)
            {
                Application.DoEvents();
                try
                {

                    Application.DoEvents();
                    this.fc.AllLights(true);
                    Thread.Sleep(15);
                    Application.DoEvents();
                    this.fc.AllLights(false);
                    Thread.Sleep(15);

                    int relay = 1;
                    while (relay <= 4)
                    {
                        Application.DoEvents();
                        for (int i = 1; i < this.fc.maxTowerNum; i++)
                        {
                            Application.DoEvents();
                            this.fc.PinWrite(i, relay, true);
                            Thread.Sleep(15);
                        }
                        for (int i = 1; i < this.fc.maxTowerNum; i++)
                        {
                            Application.DoEvents();
                            this.fc.PinWrite(i, relay, false);
                            Thread.Sleep(15);
                        }

                        relay++;
                    }
                }
                catch { }

            }
        }

        #endregion

        #region xbee Buttons

        private void btnXbeeOpenPort_Click(object sender, EventArgs e)
        {
            try
            {
                this.xb.Startup(cbXbeeComPort.Text);
            }
            catch { };
        }

        private void btnXbeeClosePort_Click(object sender, EventArgs e)
        {
            this.xb.Shutdown();
        }

        private void btnXbeeSend_Click(object sender, EventArgs e)
        {
            this.xb.Send(tbXbeeDataOut.Text);
        }

        private void xbeeTimer_Tick(object sender, EventArgs e)
        {
            if (this.xb.DataIn != null)
            {
                tbtext.Text = this.xb.DataIn.ToString() + "\r\n";
                tbtext.SelectionStart = tbtext.Text.Length;
                tbtext.Focus();
                tbtext.ScrollToCaret();
            }
            Application.DoEvents();
        }

        private void btnXbeeRecieveData_Click(object sender, EventArgs e)
        {

        }

        private void btnXbeeStopData_Click(object sender, EventArgs e)
        {

        }

        private void btnXbeeClearText_Click(object sender, EventArgs e)
        {
            this.xb.DataIn = null;
            this.xb.xbReceivedData.Clear();
            tbtext.Clear();
            tbtext.SelectionStart = tbtext.Text.Length;
            tbtext.Focus();
            tbtext.ScrollToCaret();
        }

        private void btnXbeeTest1_Click(object sender, EventArgs e)
        {

        }

        private void btnXbeeTest2_Click(object sender, EventArgs e)
        {

        }

        private void updateXbeeTextBox()
        {
            tbtext.Text = this.xb.DataIn + "\r\n";
            tbtext.SelectionStart = tbtext.Text.Length;
            tbtext.ScrollToCaret();
        }

        #endregion

        #endregion

        #region Game Tab

        #region Penalties

        #region Green Penalties
        private void lblGreenPenalty1_Click(object sender, EventArgs e)
        {
            if (lblGreenPenalty1.BackColor == Main_Control.DefaultBackColor)
            {
                lblGreenPenalty1.BackColor = Color.Lime;
                lblGreenPenalty1.ForeColor = Color.Black;
                GD.lblGreenPenalty1.BackColor = Color.Lime;
                GD.lblGreenPenalty1.ForeColor = Color.Black;
                this.game.green.penalty++;
                this.game.GameLog("Green Penalty: ADD");
            }
            else
            {
                lblGreenPenalty1.BackColor = Main_Control.DefaultBackColor;
                lblGreenPenalty1.ForeColor = Color.Lime;
                GD.lblGreenPenalty1.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenPenalty1.ForeColor = Main_Control.DefaultBackColor;
                this.game.green.penalty--;
                this.game.GameLog("Green Penalty: Subtract");
            }
        }

        private void lblGreenPenalty2_Click(object sender, EventArgs e)
        {
            if (lblGreenPenalty2.BackColor == Main_Control.DefaultBackColor)
            {
                lblGreenPenalty2.BackColor = Color.Lime;
                lblGreenPenalty2.ForeColor = Color.Black;
                GD.lblGreenPenalty2.BackColor = Color.Lime;
                GD.lblGreenPenalty2.ForeColor = Color.Black;
                this.game.green.penalty++;
                this.game.GameLog("Green Penalty: ADD");
            }
            else
            {
                lblGreenPenalty2.BackColor = Main_Control.DefaultBackColor;
                lblGreenPenalty2.ForeColor = Color.Lime;
                GD.lblGreenPenalty2.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenPenalty2.ForeColor = Main_Control.DefaultBackColor;
                this.game.green.penalty--;
                this.game.GameLog("Green Penalty: Subtract");
            }
        }

        private void lblGreenPenalty3_Click(object sender, EventArgs e)
        {
            if (lblGreenPenalty3.BackColor == Main_Control.DefaultBackColor)
            {
                lblGreenPenalty3.BackColor = Color.Lime;
                lblGreenPenalty3.ForeColor = Color.Black;
                GD.lblGreenPenalty3.BackColor = Color.Lime;
                GD.lblGreenPenalty3.ForeColor = Color.Black;
                this.game.green.penalty++;
                this.game.GameLog("Green Penalty: ADD");
            }
            else
            {
                lblGreenPenalty3.BackColor = Main_Control.DefaultBackColor;
                lblGreenPenalty3.ForeColor = Color.Lime;
                GD.lblGreenPenalty3.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenPenalty3.ForeColor = Main_Control.DefaultBackColor;
                this.game.green.penalty--;
                this.game.GameLog("Green Penalty: Subtract");
            }
        }

        private void lblGreenDQ_Click(object sender, EventArgs e)
        {
            if (lblGreenDQ.BackColor == Main_Control.DefaultBackColor)
            {
                lblGreenDQ.BackColor = Color.Lime;
                lblGreenDQ.ForeColor = Color.Black;
                GD.lblGreenDQ.BackColor = Color.Lime;
                GD.lblGreenDQ.ForeColor = Color.Black;
                this.game.green.dq = true;
                this.game.GameLog("Green DQ: True");
            }
            else
            {
                lblGreenDQ.BackColor = Main_Control.DefaultBackColor;
                lblGreenDQ.ForeColor = Color.Lime;
                GD.lblGreenDQ.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenDQ.ForeColor = Main_Control.DefaultBackColor;
                this.game.green.dq = false;
                this.game.GameLog("Green DQ: False");
            }
        }

        private void btnDisableGreen_Click(object sender, EventArgs e)
        {
            if (btnDisableGreen.BackColor == Main_Control.DefaultBackColor)
            {
                
                btnDisableGreen.BackColor = Color.Lime;
                btnDisableGreen.ForeColor = Color.Black;
                GD.lblGreenScore.BackColor = Color.Lime;
                GD.lblGreenScore.ForeColor = Color.Black;
                this.fc.RobotTransmitters(2, false, false);
                this.game.GameLog("Green Disabled = True");
            }
            else
            {
                btnDisableGreen.BackColor = Main_Control.DefaultBackColor;
                btnDisableGreen.ForeColor = Color.Lime;
                GD.lblGreenScore.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenScore.ForeColor = Color.Lime;
                this.fc.RobotTransmitters(2, true, true);
                this.game.GameLog("Green Disabled = False");
            }
        }
        #endregion

        #region Red Penalties
        private void lblRedPenalty1_Click(object sender, EventArgs e)
        {
            if (lblRedPenalty1.BackColor == Main_Control.DefaultBackColor)
            {
                lblRedPenalty1.BackColor = Color.Red;
                lblRedPenalty1.ForeColor = Color.Black;
                GD.lblRedPenalty1.BackColor = Color.Red;
                GD.lblRedPenalty1.ForeColor = Color.Black;
                this.game.red.penalty++;
                this.game.GameLog("Red Penalty: ADD");
            }
            else
            {
                lblRedPenalty1.BackColor = Main_Control.DefaultBackColor;
                lblRedPenalty1.ForeColor = Color.Red;
                GD.lblRedPenalty1.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedPenalty1.ForeColor = Main_Control.DefaultBackColor;
                this.game.red.penalty--;
                this.game.GameLog("Red Penalty: Subtract");
            }
        }

        private void lblRedPenalty2_Click(object sender, EventArgs e)
        {
            if (lblRedPenalty2.BackColor == Main_Control.DefaultBackColor)
            {
                lblRedPenalty2.BackColor = Color.Red;
                lblRedPenalty2.ForeColor = Color.Black;
                GD.lblRedPenalty2.BackColor = Color.Red;
                GD.lblRedPenalty2.ForeColor = Color.Black;
                this.game.red.penalty++;
                this.game.GameLog("Red Penalty: ADD");
            }
            else
            {
                lblRedPenalty2.BackColor = Main_Control.DefaultBackColor;
                lblRedPenalty2.ForeColor = Color.Red;
                GD.lblRedPenalty2.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedPenalty2.ForeColor = Main_Control.DefaultBackColor;
                this.game.red.penalty--;
                this.game.GameLog("Red Penalty: Subtract");
            }
        }

        private void lblRedPenalty3_Click(object sender, EventArgs e)
        {
            if (lblRedPenalty3.BackColor == Main_Control.DefaultBackColor)
            {
                lblRedPenalty3.BackColor = Color.Red;
                lblRedPenalty3.ForeColor = Color.Black;
                GD.lblRedPenalty3.BackColor = Color.Red;
                GD.lblRedPenalty3.ForeColor = Color.Black;
                this.game.red.penalty++;
                this.game.GameLog("Red Penalty: ADD");
            }
            else
            {
                lblRedPenalty3.BackColor = Main_Control.DefaultBackColor;
                lblRedPenalty3.ForeColor = Color.Red;
                GD.lblRedPenalty3.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedPenalty3.ForeColor = Main_Control.DefaultBackColor;
                this.game.red.penalty--;
                this.game.GameLog("Red Penalty: Subtract");
            }
        }

        private void lblRedDQ_Click(object sender, EventArgs e)
        {
            if (lblRedDQ.BackColor == Main_Control.DefaultBackColor)
            {
                lblRedDQ.BackColor = Color.Red;
                lblRedDQ.ForeColor = Color.Black;
                GD.lblRedDQ.BackColor = Color.Red;
                GD.lblRedDQ.ForeColor = Color.Black;
                this.game.red.dq = true;
                this.game.GameLog("Red DQ: True");
            }
            else
            {
                lblRedDQ.BackColor = Main_Control.DefaultBackColor;
                lblRedDQ.ForeColor = Color.Red;
                GD.lblRedDQ.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedDQ.ForeColor = Main_Control.DefaultBackColor;
                this.game.red.dq = false;
                this.game.GameLog("Red DQ: False");
            }
        }

        private void btnDisableRed_Click(object sender, EventArgs e)
        {
            if (btnDisableRed.BackColor == Main_Control.DefaultBackColor)
            {

                btnDisableRed.BackColor = Color.Red;
                btnDisableRed.ForeColor = Color.Black;
                GD.lblRedScore.BackColor = Color.Red;
                GD.lblRedScore.ForeColor = Color.Black;
                this.fc.RobotTransmitters(2, false, false);
                this.game.GameLog("Red Disabled = True");
            }
            else
            {
                btnDisableRed.BackColor = Main_Control.DefaultBackColor;
                btnDisableRed.ForeColor = Color.Red;
                GD.lblRedScore.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedScore.ForeColor = Color.Red;
                this.fc.RobotTransmitters(2, true, true);
                this.game.GameLog("Red Disabled = False");
            }
        }

        #endregion

        #endregion

        #region Game Controls

        private void btnStartGame_Click(object sender, EventArgs e)
        {
            disableGameButtons();
            btnEStop.BackColor = Main_Control.DefaultBackColor;
            btnStartGame.BackColor = Color.LimeGreen;
            ClearDisplay();
            this.game.GameStartUp();
            this.time.countDownStart(2, 1);
            this.time.elapsedTime.Restart();
            this.time.timesUp = false;

            while (!this.game.gameDone && !this.game.STOP)
            {
                this.game.MainGame();
                timeKeeper();
                updateDisplays();
                Application.DoEvents();
            }

            this.game.GameShutDown();
            this.game.GameLog("Game Stopped");

            while (!this.game.STOP)
            {
                Application.DoEvents();
            }

            this.fc.FieldAllOff();
            this.game.GameLog("Field Off");
            enableGameButtons();
        }

        private void btnPracticeMode_Click(object sender, EventArgs e)
        {
            disableGameButtons();
            btnEStop.BackColor = Main_Control.DefaultBackColor;
            btnPracticeMode.BackColor = Color.LimeGreen;
            ClearDisplay();
            this.game.GameStartUp(true, true);
            this.time.countDownStart(2, 1);
            this.time.elapsedTime.Restart();
            this.time.timesUp = false;

            while (!this.game.gameDone && !this.game.STOP)
            {
                this.game.MainGame();
                updateDisplays();
                Application.DoEvents();
            }

            this.game.GameShutDown();
            this.game.GameLog("Game Stopped");
            this.game.practiceMode = false;

            this.fc.FieldAllOff();
            this.game.GameLog("Field Off");
            enableGameButtons();
        }

        private void btnAutoMode_Click(object sender, EventArgs e)
        {
            disableGameButtons();
            btnEStop.BackColor = Main_Control.DefaultBackColor;
            btnAutoMode.BackColor = Color.LimeGreen;
            ClearDisplay();
            this.game.GameStartUp(true, true);
            this.game.GameLog("Auto Mode Started");
            this.time.countDownStart(2, 1);
            this.time.elapsedTime.Restart();
            this.time.timesUp = false;

            while (!this.game.gameDone && !this.game.STOP)
            {
                this.game.AutoMode();
                timeKeeper();
                updateDisplays();
                Application.DoEvents();
            }

            this.game.GameShutDown();
            this.game.GameLog("Auto Mode Stopped");
            btnAutoMode.BackColor = Main_Control.DefaultBackColor;

            this.fc.FieldAllOff();
            this.game.GameLog("Field Off");
            enableGameButtons();
        }

        private void btnMiddleMode_Click(object sender, EventArgs e)
        {
            disableGameButtons();
            btnEStop.BackColor = Main_Control.DefaultBackColor;
            btnMiddleMode.BackColor = Color.LimeGreen;
            ClearDisplay();
            this.game.GameStartUp(false, true);
            this.game.midMode = true;
            this.game.GameLog("Middle Mode Started");
            this.time.countDownStart(2, 1);
            this.time.elapsedTime.Restart();
            this.time.timesUp = false;

            while (!this.game.gameDone && !this.game.STOP)
            {
                this.game.MidMode();
                updateDisplays();
                Application.DoEvents();
            }

            this.game.GameShutDown();
            this.game.GameLog("Middle Mode Stopped");
            btnMiddleMode.BackColor = Main_Control.DefaultBackColor;
            this.game.practiceMode = false;

            this.fc.FieldAllOff();
            this.game.GameLog("Field Off");
            enableGameButtons();
        }

        private void btnEStop_Click(object sender, EventArgs e)
        {
            //Turn on all Hub Channel
            this.ow.HubAllMainsOn();

            btnEStop.BackColor = Color.Red;
            btnStartGame.BackColor = Main_Control.DefaultBackColor;
            btnPracticeMode.BackColor = Main_Control.DefaultBackColor;
            this.game.STOP = true;
            enableGameButtons();
        }

        private void btnMatchNext_Click(object sender, EventArgs e)
        {
            if (this.game.STOP)
            {
                matchNumber++;
                this.game.matchNumber = matchNumber;
                lblMatchNumber.Text = "Match " + matchNumber.ToString();
                GD.lblMatchNumber.Text = "Match " + matchNumber.ToString();
                GetTeamNames();
                ClearDisplay();
            }
        }

        private void btnMatchPrev_Click(object sender, EventArgs e)
        {
            if (this.game.STOP)
            {
                if (matchNumber > 0) matchNumber--;
                this.game.matchNumber = matchNumber;
                lblMatchNumber.Text = "Match " + matchNumber.ToString();
                GD.lblMatchNumber.Text = "Match " + matchNumber.ToString();
                GetTeamNames();
                ClearDisplay();
            }
        }

        private void lblMatchNumber_Click(object sender, EventArgs e)
        {
            GetTeamNames();
        }

        private void btnGameDisplay_Click(object sender, EventArgs e)
        {
            if (Screen.AllScreens.Length > 1)//Check for Multiple Displays
            {

                // Important !
                GD.StartPosition = FormStartPosition.Manual;

                // Get the second monitor screen
                Screen screen = GetSecondaryScreen();

                // set the location to the top left of the second screen
                GD.Location = screen.WorkingArea.Location;

                // set it fullscreen
                GD.Size = new Size(screen.WorkingArea.Width, screen.WorkingArea.Height);

                // Show the form
                GD.Show();//Shows Display on Second Display

            }
            else GD.Show(); //Shows Display on the only display
            btnGameDisplay.Visible = false; //Disables the button
        }

        private void btnScoreGame_Click(object sender, EventArgs e)
        {
            Score score = new Score(game);
            score.Show();

            while (!score.finalScore)
            {
                Application.DoEvents();
            }

            ScoreGame();
            RecordGame();

            score.Close();

            btnEStop.BackColor = Color.Red;
            btnStartGame.BackColor = Main_Control.DefaultBackColor;
            btnPracticeMode.BackColor = Main_Control.DefaultBackColor;
            this.game.STOP = true;

            lblGreenScore.Text = this.game.green.finalScore.ToString();
            lblRedScore.Text = this.game.red.finalScore.ToString();
            GD.lblGreenScore.Text = this.game.green.finalScore.ToString();
            GD.lblRedScore.Text = this.game.red.finalScore.ToString();

            //Turn on all Hub Channel
            this.ow.HubAllMainsOn();
        }

        private void TimerGameClock_Tick(object sender, EventArgs e)
        {
        //    TimeSpan sp = GameClock - DateTime.Now;
        //    if ((sp.Minutes == 0) && (sp.Seconds == 0))
        //    {
        //        TimerGameClock.Stop();
        //        lblGameClock.Text = ("0:00");
        //        this.game.gameDone = true;
        //        this.game.STOP = true;
        //    }
        //    if (this.game.autoMode && this.game.autoModeTime <= stopWatch.Elapsed.Seconds)
        //    {
        //        lblGameClock.ForeColor = Color.Black;
        //        GD.lblGameClock.ForeColor = Color.Black;
        //        this.game.autoMode = false;
        //        stopWatch.Stop();
        //    }
        }

        private void lblGreenScore_Click(object sender, EventArgs e)
        {
            ClearDisplay();
        }

        private void lblRedScore_Click(object sender, EventArgs e)
        {
            ClearDisplay();
        }

        private void lblGameClock_Click(object sender, EventArgs e)
        {
            ClearDisplay();
        }

        private void btnDebug_Click(object sender, EventArgs e)
        {
            this.ow.debug = !this.ow.debug;
            if (this.ow.debug)
            {
                btnDebug.Text = "Debug Mode ON";
                btnDebug.ForeColor = Color.Green;
            }
            else
            {
                btnDebug.Text = "Debug";
                btnDebug.ForeColor = DefaultForeColor;
            }
        }

        private void ScoreGame()
        {
            this.game.red.finalScore = 0;
            this.game.green.finalScore = 0;

            //Add convert additional points to intergers here

            this.game.red.finalScore = this.game.red.score;       //Do math here for final score
            this.game.green.finalScore = this.game.green.score;   //Do math here for final score

            this.game.red.finalScore = this.game.red.finalScore - (this.game.red.penalty * 15);
            this.game.green.finalScore = this.game.green.finalScore - (this.game.green.penalty * 15);

            if (this.game.red.dq || this.game.red.penalty == 3)
            {
                this.game.red.finalScore = 0;
                this.game.red.matchResult = "L";
            }
            if (this.game.green.dq || this.game.green.penalty == 3)
            {
                this.game.green.finalScore = 0;
                this.game.green.matchResult = "L";
            }

            if (this.game.green.finalScore > this.game.red.finalScore)
            {
                this.game.green.matchResult = "W";
                this.game.red.matchResult = "L";
            }
            else if (this.game.red.finalScore > this.game.green.finalScore)
            {
                this.game.red.matchResult = "W";
                this.game.green.matchResult = "L";
            }
            else if (this.game.green.finalScore == this.game.red.finalScore && !this.game.green.dq && !this.game.red.dq)
            {
                this.game.red.matchResult = "T";
                this.game.green.matchResult = "T";
            }
        }

        private void RecordGame()
        {
            string file = "\\Match " + matchNumber.ToString() + " - Score";
            string file2 = "\\Match Scores";
            string folder = "Matches\\" + "Match " + matchNumber.ToString();
            string folder2 = "Matches\\";

            string greenTeam = (matchNumber.ToString() + "\t" + lblGreenTeam.Text.ToString() + "\t" + this.game.green.score.ToString() + "\t" + this.game.green.finalScore.ToString()
                               + "\t" + this.game.green.penalty.ToString() + "\t" + this.game.green.dq.ToString() + "\t" + this.game.green.matchResult);
            string redTeam = (matchNumber.ToString() + "\t" + lblRedTeam.Text.ToString() + "\t" + this.game.red.score.ToString() + "\t" + this.game.red.finalScore.ToString()
                             + "\t" + this.game.red.penalty.ToString() + "\t" + this.game.red.dq.ToString() + "\t" + this.game.red.matchResult);
            string field = ("Something 1" + "\t" + "Something 2" + "\t" + "Something 3" + "\t" + "Something 4");

            string text = ("\r\n" + greenTeam + "\r\n" + redTeam + "\r\n" + field);

            try
            {
                this.lw.WriteLog(text, file, folder);
                this.lw.WriteLog(text, file2, folder2);
            }
            catch
            {
                MessageBox.Show("Game Score was not recorded");
                return;
            }

        }

        private void GetTeamNames()
        {
            string greenTeam = null;
            string redTeam = null;
            string content = null;
            string path = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Desktop\YBOT Field Control Program Files\Setup Files");
            string file = path + @"\Teams.txt";

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
                path = null;
            }

            try
            {
                if (File.Exists(file))
                {
                    //StreamReader sr = new StreamReader(file, System.Text.Encoding.Default);
                    Stream stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    StreamReader sr = new StreamReader(stream);

                    for (int i = 0; i < matchNumber; i++)
                    {
                        content = sr.ReadLine();
                        string[] teams = content.Split(new string[] { "\t" }, StringSplitOptions.None);//Delimited the Tab keycode
                        greenTeam = teams[0];
                        redTeam = teams[1];
                    }
                    sr.Close();
                    sr.Dispose();
                }
                else
                {
                    greenTeam = "Green Team";
                    redTeam = "Red Team";
                }
            }
            catch
            {
                greenTeam = "Green Team";
                redTeam = "Red Team";
            }
            if (greenTeam == null) greenTeam = "Green Team";
            if (redTeam == null) redTeam = "Red Team";


            lblGreenTeam.Text = greenTeam;
            lblRedTeam.Text = redTeam;
            GD.lblGreenTeam.Text = greenTeam;
            GD.lblRedTeam.Text = redTeam;
        }

        private void timeKeeper()
        {
            if (this.time.timesUp)
            {
                lblGameClock.Text = ("0:00");
                this.game.gameDone = true;
                //this.game.STOP = true;
            }

            else if (this.game.autoMode && !this.time.Timer(this.game.autoModeTime))
            {
                lblGameClock.ForeColor = Color.Red;
                GD.lblGameClock.ForeColor = Color.Red;
            }

            else if (this.game.autoMode && this.time.Timer(this.game.autoModeTime)) this.game.midMode = true;
               
            else if (this.game.midMode && !this.time.Timer(this.game.midModeTime))
            {
                lblGameClock.ForeColor = Color.Blue;
                GD.lblGameClock.ForeColor = Color.Blue;
            }

            else
            {
                lblGameClock.ForeColor = Color.Black;
                GD.lblGameClock.ForeColor = Color.Black;
                this.game.endMode = true;
            }
        }

        private void disableGameButtons()
        {
            btnStartGame.Enabled = false;
            btnAutoMode.Enabled = false;
            btnMiddleMode.Enabled = false;
            btnPracticeMode.Enabled = false;
        }

        private void enableGameButtons()
        {
            btnStartGame.Enabled = true;
            btnAutoMode.Enabled = true;
            btnMiddleMode.Enabled = true;
            btnPracticeMode.Enabled = true;
        }

        #endregion

        #region Display

        private void updateDisplays()
        {
            lblGameClock.Text = this.time.countDownStatus();
            GD.lblGameClock.Text = lblGameClock.Text.ToString();
            lblGreenScore.Text = this.game.green.score.ToString();
            lblRedScore.Text = this.game.red.score.ToString();
            GD.lblGreenScore.Text = this.game.green.score.ToString();
            GD.lblRedScore.Text = this.game.red.score.ToString();

        }

        public Screen GetSecondaryScreen()
        {
            if (Screen.AllScreens.Length == 1)
            {
                return null;
            }

            foreach (Screen screen in Screen.AllScreens)
            {
                if (screen.Primary == false)
                {
                    return screen;
                }
            }

            return null;
        }

        public void updateTextbox_Log(string log)
        {
            string path = (this.lw.YBOTFilePath() + @"\Logs");
            string file = path + log;
            string text = null;

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
                path = null;
            }

            try
            {
                StreamReader logfile = new StreamReader(file); //Read the file
                if (File.Exists(file))                                     //If file is there
                {
                    tbtext.Clear();
                    do
                    {
                        File.OpenRead(file);                                   //Open the file
                        text = logfile.ReadLine();                      //Read each line

                        try
                        {
                            tbtext.AppendText(text + "\r\n");
                            tbtext.Focus();
                            tbtext.ScrollToCaret();
                        }
                        catch (Exception e)
                        {
                            Console.Out.WriteLine(e);
                        }
                    } while (text != null);
                }
                logfile.Close();
            }
            catch
            {
                return;
            }
        }

        public void updateTextbox(string text)
        {
            try
            {
                tbtext.AppendText(text + "\r\n");
                tbtext.Focus();
                tbtext.ScrollToCaret();
            }
            catch
            {
            }
        }

        private void frmLocateTowers_Load(object sender, EventArgs e)
        {
            frmLocateNodes.Focus();
        }

        private void btnReadLog_Click(object sender, EventArgs e)
        {
            updateTextbox_Log(@"\YBOT_1wirelog.txt");
        }

        private void ClearDisplay()
        {
            if (this.game.STOP)
            {
                lblGameClock.Text = "2:00";
                GD.lblGameClock.Text = "2:00";

                lblRedScore.Text = "000";
                lblGreenScore.Text = "000";
                GD.lblGreenScore.Text = "000";
                GD.lblRedScore.Text = "000";

                lblGreenPenalty1.BackColor = Main_Control.DefaultBackColor;
                lblGreenPenalty1.ForeColor = Color.Lime;
                GD.lblGreenPenalty1.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenPenalty1.ForeColor = Main_Control.DefaultBackColor;

                lblGreenPenalty2.BackColor = Main_Control.DefaultBackColor;
                lblGreenPenalty2.ForeColor = Color.Lime;
                GD.lblGreenPenalty2.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenPenalty2.ForeColor = Main_Control.DefaultBackColor;

                lblGreenPenalty3.BackColor = Main_Control.DefaultBackColor;
                lblGreenPenalty3.ForeColor = Color.Lime;
                GD.lblGreenPenalty3.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenPenalty3.ForeColor = Main_Control.DefaultBackColor;

                lblGreenDQ.BackColor = Main_Control.DefaultBackColor;
                lblGreenDQ.ForeColor = Color.Lime;
                GD.lblGreenDQ.BackColor = Main_Control.DefaultBackColor;
                GD.lblGreenDQ.ForeColor = Main_Control.DefaultBackColor;

                lblRedPenalty1.BackColor = Main_Control.DefaultBackColor;
                lblRedPenalty1.ForeColor = Color.Red;
                GD.lblRedPenalty1.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedPenalty1.ForeColor = Main_Control.DefaultBackColor;

                lblRedPenalty2.BackColor = Main_Control.DefaultBackColor;
                lblRedPenalty2.ForeColor = Color.Red;
                GD.lblRedPenalty2.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedPenalty2.ForeColor = Main_Control.DefaultBackColor;

                lblRedPenalty3.BackColor = Main_Control.DefaultBackColor;
                lblRedPenalty3.ForeColor = Color.Red;
                GD.lblRedPenalty3.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedPenalty3.ForeColor = Main_Control.DefaultBackColor;

                lblRedDQ.BackColor = Main_Control.DefaultBackColor;
                lblRedDQ.ForeColor = Color.Red;
                GD.lblRedDQ.BackColor = Main_Control.DefaultBackColor;
                GD.lblRedDQ.ForeColor = Main_Control.DefaultBackColor;

            }
        }

        #endregion

        #endregion

        //------------------------------------------------------------------------------------------------\\
        //Current year's game methods
        //------------------------------------------------------------------------------------------------\\

        private void btnGreenPlus_Click(object sender, EventArgs e)
        {
        }

        private void btnGreenMinus_Click(object sender, EventArgs e)
        {
        }

        private void btnRedPlus_Click(object sender, EventArgs e)
        {
        }

        private void btnRedMinus_Click(object sender, EventArgs e)
        {
        }

   }
}
